$(document).ready(function(){
    addjumpPagesEvent();
    showCartCount();
    addGoodsList();
    addClickEvent();
})
function addjumpPagesEvent(){
    $("#home").click(function(){
        location.assign("../html/home.html");})
    $("#shoppingCart").click(function(){
        location.assign("../html/shoppingCart.html");})
}
function showCartCount(){
    $("#cartCount").html(localStorage.getItem("cartCount")||0);
}
function saveCount(){
    var count= $("#cartCount").html()||0;
        count++;
       $("#cartCount").html(count);
    localStorage.setItem("cartCount",count);
}
function addClickEvent(){
   $.getJSON("../js/productInfo.json",function(info){
       var goodsName=JSON.parse(localStorage.getItem("goodsName"))||[];
       $(".button").click( function(){
           saveCount();
           var ID=this.id;
           var cartName=info[ID].name;
           addCartCount(ID,cartName,goodsName,info);
           addGoodsNameArray(ID,cartName,goodsName,info);
       })
   })
}
function addCartCount(ID,cartName,goodsName,info){
    console.log("加入购物车");
    var goodsInfo=JSON.parse(localStorage.getItem("goodsInfo"))||[];
    if(goodsName.indexOf(cartName)==-1){
        info[ID].count=1;
        goodsInfo.push(info[ID]);
    }else{
        _.each(goodsInfo,function(item){
            if(ID==item.id){
                item.count++;
            }
        })
    }
    localStorage.setItem("goodsInfo",JSON.stringify(goodsInfo));
}
function  addGoodsNameArray(ID,cartName,goodsName,info){
    if(goodsName.indexOf(cartName)==-1){
        goodsName.push(info[ID].name);
        localStorage.setItem("goodsName",JSON.stringify(goodsName));
    }
}
function addGoodsList(){
    $.getJSON("../js/productInfo.json",function(info){
        $("#trPemp").tmpl(info).appendTo('#tableList');
    })
}